<template>
    <div class="main relative">
        <div class="h100 flex fd-column jc-space-between">
            <div class="head pl-m pr-m flex ai-center">
                <p class="f1 fs-m">{{chatTarget.username}}</p>
                <i class="iconfont icon-more hoverIcon"></i>
            </div>
            <scroll-container class="content f1"
                              ref="messageList"
                              :totalLength="chatData.totalLength"
                              :listLength="chatMessage.length"
                              @loadMore="loadMore"
                              always-bottom
            >
                <ul class="pl-m pr-m pt-xs pb-xs" ref="mainContent" @click="fileDown">
                    <li v-for="message in chatMessage" :key="message._id">
                        <div class="mb-s" :class="message.poster === userData.username ? 'userSite' : 'opposite'">
                            <p class="time">{{message.updatedTime}}</p>
                            <div class="flex content">
                                <div class="profile relative">
                                    <div class="avatar" v-if="message.poster !== userData.username" :style="{
                                        backgroundImage: `url(${chatTarget.profile.url})`,
                                        backgroundSize: chatTarget.profile.scale / 5 * 3 + 'px',
                                        backgroundPosition: `${chatTarget.profile.pos.x / 5 * 3}px ${chatTarget.profile.pos.y / 5 * 3}px`,
                                    }">
                                        <img src="../../../assets/user-circle.png" alt="" v-if="chatTarget.profile.url === ''" style="width: 100%;">
                                    </div>
                                    <div class="avatar" v-else :style="{
                                        backgroundImage: `url(${userData.profile.url})`,
                                        backgroundSize: userData.profile.scale / 5 * 3 + 'px',
                                        backgroundPosition: `${userData.profile.pos.x / 5 * 3}px ${userData.profile.pos.y / 5 * 3}px`,
                                    }">
                                        <img src="../../../assets/user-circle.png" alt="" v-if="userData.profile.url === ''" style="width: 100%;">
                                    </div>
                                </div>
                                <div class="message">
                                    <p class="username">{{chatTarget.username}}</p>
                                    <div class="dialog" :class="{'imgBox': message.textType !== 'text'}">
                                        <div class="arrow"></div>
                                        <div class="fs-s" v-html="message.preText"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </scroll-container>
            <text-edit class="textEdit" ref="textEdit"></text-edit>
        </div>
        <div v-show="!isSelectChat" class="mainMask flex jc-center ai-center">
            还没有选中好友发起聊天
        </div>
    </div>
</template>

<script>
    import textEdit from './TextEdit';

    export default {
        name: "chatContent",
        components: {
            'textEdit': textEdit,
        },
        data() {
            return {

            }
        },
        computed: {
            userData() {
                return this.$store.state.userData;
            },
            chatData() {
                return this.$store.state.chatData;
            },
            chatTarget() {
                return this.$store.state.chatTarget;
            },
            chatMessage() {
                return this.$store.state.chatMessage;
            },
            isSelectChat() {
                return Object.keys(this.chatTarget).length !== 0;
            }
        },
        watch: {
            'this.$store.state.imgQueue': function(newData) {
                if (newData.length > 1) {
                    this.$nextTick(() => {
                        this.checkItemToAdd(newData);
                    })
                }
            }
        },
        methods: {
            initMessage() {
                this.$refs.messageList.init();
            },

            checkItemToAdd(queue) {
                let mList = this.$refs.mainContent.children;
                if (queue !== undefined) {
                    for (let i = 0; i < queue.length; i++) {
                        this.addEventUpdate(mList[queue[0]].children[0]
                            .children[1].children[1]
                            .children[1].children[1].children[0]);
                    }
                } else {
                    this.addEventUpdate(mList[mList.length - 1].children[0]
                        .children[1].children[1]
                        .children[1].children[1].children[0]);
                }
            },

            addEventUpdate(target) {
                target.addEventListener('load', () => {
                    this.messageListUpdate();
                })
            },

            messageListUpdate() {
                this.$nextTick(() => {
                    this.$refs.messageList.update(true)
                })
            },

            updateMessage(res) {
                let {mID, oppositeID, post, unreadAdd} = res;

                //格式化时间
                let time = new Date(post.time);

                for (let i = 0; i < this.userData.currentMessages.length; i++) {
                    if (this.userData.currentMessages[i].content._id === mID) {
                        this.$store.commit('updateCurrentMessage', {
                            index: i,
                            time: time,
                            post: post,
                            oppositeID: oppositeID,
                        });

                        if (this.$store.state.chatTarget._id === oppositeID) {
                            //初始化输入状态
                            this.resetEdit();
                            //清除服务器上的未读
                            this.$socket.emit('clearUnread', mID);
                            //提醒滚动条组件更新
                            if (post.textType === 'img') {
                                this.$nextTick(this.checkItemToAdd);
                            } else {
                                this.messageListUpdate();
                            }
                        }
                        return
                    }
                }

                //没有发过信息的话直接显示就行了
                post.updatedTime = time.toISOString().slice(5, 10)
                    + ' ' + time.toTimeString().slice(0, 5);

                let opposite = null;
                for (let user of this.userData.friends) {
                    if (user._id === oppositeID) {
                        opposite = user;
                        break;
                    }
                }
                let newMessage = {
                    opposite: opposite,
                    content: {
                        _id: mID,
                        users: [this.userData._id, oppositeID],
                        mList: [post],
                        listLength: 1,
                    },
                    unread: 0,
                }

                this.$store.commit('addNewCurrentMessage', {
                    target: newMessage,
                    oppositeID: oppositeID,
                    mID: mID,
                    unreadAdd: unreadAdd,
                });
                if (this.$store.state.chatTarget._id === oppositeID) {
                    this.resetEdit();
                    this.$socket.emit('clearUnread', mID);
                }
            },

            resetEdit() {
                this.$refs.textEdit.resetEdit();
            },

            loadMore() {
                this.$socket.emit('loadMoreMessage', {
                    limit: this.chatData.mLimit,
                    mID: this.chatData.mID,
                })
            },

            addMore(data) {
                if (this.chatData.mID === data.mID) {
                    this.$store.commit('addMoreMessage', data.moreMessage)
                }
                this.$refs.messageList.resetLoadStatus();
            },

            fileDown(e) {
                if (e.target.classList[0] === 'download') {
                    const download = document.createElement('a');
                    download.href = e.target.dataset.url;
                    download.download = e.target.dataset.url;
                    download.target = '_blank';
                    download.click();
                }
            },
        },
        created() {
            this.$socket.on('updateMessage', this.updateMessage);
            this.$socket.on('addMoreMessage', this.addMore);
        }
    }
</script>

<style scoped lang="scss">
    .main {
        width: 750px;
        min-width: 320px;
        background-color: rgb(238 238 238);
        overflow: hidden;

        .head {
            color: grey;
            height: 50px;
            border-bottom: 1px solid #d9d9d9;
            flex-shrink: 0;

            .iconfont {
                cursor: pointer;
                font-size: 25px;
            }
        }

        .content {
            position: relative;

            .opposite,
            .userSite {
                padding-top: 5px;

                .content {
                    width: 100%;
                    overflow: initial;
                }

                .time {
                    color: #a3a7ae;
                    text-align: center;
                }

                .profile {
                    width: 30px;
                    height: 30px;
                    border-radius: 50%;
                    background-color: #eee;
                    flex-shrink: 0;

                    .avatar {
                        width: 30px;
                        height: 30px;
                        border-radius: 50%;
                    }
                }

                .username {
                    color: #a3a7ae;
                    margin-bottom: 3px;
                }

                .dialog {
                    position: relative;
                    max-width: 350px;
                    padding: 10px 16px;
                    border-radius: 10px;
                    background-color: white;
                    box-shadow: 0 5px 12px 0 #ddd;

                    &.imgBox {
                        padding: 0 0;
                        background-color: white !important;
                    }

                    p {
                        max-width: 350px;
                        white-space: pre-wrap;
                        word-break: break-all;
                        overflow-wrap: break-word;
                    }

                    ::v-deep {
                        .iconfont {
                            padding: 1px 1px;
                            color: #686e79;
                            font-size: 20px;
                        }

                        img {
                            display: block;
                            max-width: 350px;
                            max-height: 300px;
                            border-radius: 10px;
                        }

                        video {
                            width: 100%;
                            border-radius: 10px;
                        }

                        .file {
                            display: flex;
                            align-items: center;
                            position: relative;
                            padding: 0 20px;
                            box-sizing: border-box;
                            border-radius: 10px;
                            width: 250px;
                            height: 80px;
                            cursor: pointer;
                            background-color: white;

                            .iconfont {
                                font-size: 30px;
                                margin-right: 20px;
                                flex-shrink: 0;
                            }

                            p {
                                flex: 1;
                                width: 100%;
                                overflow: hidden;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                            }

                            .download {
                                position: absolute;
                                top: 0;
                                left: 0;
                                width: 100%;
                                height: 100%;
                            }
                        }
                    }
                }
            }

            .opposite {
                .message {
                    padding-left: 8px;

                    .arrow {
                        position: absolute;
                        width: 0;
                        height: 0;
                        top: 10px;
                        left: -10px;
                        border-top: 10px solid white;
                        border-left: 10px solid transparent;
                    }
                }
            }

            .userSite {
                .content {
                    flex-direction: row-reverse;

                    .message {
                        padding-top: 10px;
                        padding-right: 10px;

                        .username {
                            display: none;
                        }

                        .dialog {
                            background-color: #e5f3fd;
                        }

                        .arrow {
                            position: absolute;
                            width: 0;
                            height: 0;
                            top: 10px;
                            right: -8px;
                            border-top: 10px solid #e5f3fd;
                            border-right: 10px solid transparent;
                        }
                    }
                }
            }

            .scroll {
                position: absolute;
                right: 0;
                top: 0;
                width: 5px;
                height: 100%;
                z-index: 100;

                .bar {
                    position: absolute;
                    width: 5px;
                    height: 50px;
                    background-color: rgb(82, 85, 91);
                    border-radius: 20px;
                    transition: background-color 1s;
                    cursor: pointer;
                }
            }
        }

        .textEdit {
            height: 160px;
            border-top: 1px solid #ddd;
            flex-shrink: 0;
        }

        .mainMask {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: #eee;
            color: #555;
        }
    }
</style>